package database;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author link3988
 */

import java.util.*;
import java.io.*;

public class Database {

    ArrayList<Instructor> instructors;
    ArrayList<Student> students;
    ArrayList<Administrator> administrators;



    public Database()
    {
        instructors = new ArrayList();
        students = new ArrayList();
        administrators = new ArrayList();

        loadUsers();

    }

    /** Reads the database file, decrypts it, and loads
     * all students into the students array, all instructors
     * into the instructors array, and all administrators into
     * the administrator array.
     */
    private void loadUsers()
    {
        //Load the three arrays with information from the file.
        File file = null;
		//JFileChooser chooser = new JFileChooser(".");
        //int status = chooser.showOpenDialog(null);
	    //if (status == JFileChooser.APPROVE_OPTION)
	    file = new File("roster.txt");
        try
        {
            BufferedReader inputFile = new BufferedReader( new FileReader(file) );
            String tempID = "";
            String tempstyle = "";
            String temppass = "";
            String line = inputFile.readLine();
            line = inputFile.readLine();
            while(!line.equals("Administrators"))
            {
                StringTokenizer st = new StringTokenizer(line, " ");
	            tempID = decrypt(st.nextToken());
                tempstyle = decrypt(st.nextToken());
                students.add(new Student(tempID, tempstyle));
                line = inputFile.readLine();
            }
            line = inputFile.readLine();
            while(!line.equals("Instructors"))
            {
                   StringTokenizer st = new StringTokenizer(line, " ");
                   tempID = decrypt(st.nextToken());
                   temppass = decrypt(st.nextToken());
                   administrators.add(new Administrator(tempID, temppass));
                   line = inputFile.readLine();
            }
            line = inputFile.readLine();
                while(line != null)
                {
                    StringTokenizer st = new StringTokenizer(line, " ");
                    tempID = decrypt(st.nextToken());
                    temppass = decrypt(st.nextToken());
                    instructors.add(new Instructor(tempID, temppass));
                    line = inputFile.readLine();
                }

            System.out.println(instructors);
            System.out.println(students);
            System.out.println(administrators);
            inputFile.close();

        }
        catch(java.io.IOException e)
        {
            System.out.println("File not found.");
        }
    }

    /*Adds a new instructor to the list of instructors including his
     * ID and password.*/
    public void addInstructor(String ID, String pass)
    {
        instructors.add(new Instructor(ID, pass));
    }

    /*Adds a new student to the list of instructors including his
     * ID and learning style.*/
    public void addStudent(String ID, String style)
    {
        students.add(new Student(ID, style));
        //writeToFile();
    }

    /*Adds a new administrator to the list of instructors including his
     * ID and password.*/
    public void addAdministrator(String ID, String pass)
    {
        administrators.add(new Administrator(ID, pass));
    }

    /*Removes the specified instructor from the list.
     * only removes the first instance.
     * */
    public void removeInstructor(String ID)
    {
        for(int i = 0; i < instructors.size(); i++)
        {
            if(instructors.get(i).getID().equals(ID))
            {
                instructors.remove(i);
                break;
            }
        }
    }

    /*Removes the specified instructor from the list.
     * only removes the first instance.
     * */
    public void removeStudent(String ID)
    {
        for(int i = 0; i < students.size(); i++)
        {
            if(students.get(i).getID().equals(ID))
            {
                students.remove(i);
                break;
            }
        }
    }

    /*Removes the specified administrator from the list.
     * only removes the first instance.
     * */
    public void removeAdministrator(String ID)
    {
        for(int i = 0; i < administrators.size(); i++)
        {
            if(administrators.get(i).getID().equals(ID))
            {
                administrators.remove(i);
                break;
            }
        }
    }

    /* Gets the student with the specified ID number and
     * sets his learning style to the specified
     * newStyle.
     * */
    public void editStyle(String ID, String newStyle)
    {
       for(int i = 0; i < students.size(); i++)
        {
            if(students.get(i).getID().equals(ID))
            {
                students.get(i).editStyle(newStyle);
                break;
            }
        }
    }

    //Clears the database.
    public void clear()
    {
        students.clear();
        administrators.clear();
        instructors.clear();
    }

    /* Writes the lists of students, administrators, and instructors
     * to the storage file.
     * */
     public void writeToFile()
     {
         FileOutputStream out;
                PrintStream p;

                try
                {
                        // Create a new file output stream
                        // connected to the database file
                        out = new FileOutputStream("roster.txt");

                        // Connect print stream to the output stream
                        p = new PrintStream(out);
                        String temp = "";

                        p.println("Students");

                        for(int i = 0; i < students.size(); i++)
                        {
                            temp = students.get(i).toString();
                            temp = decrypt(temp);
                            p.println(temp);
                        }

                        p.println("Administrators");
                        for(int j = 0; j < administrators.size(); j++)
                        {
                            temp = administrators.get(j).toString();
                            temp = decrypt(temp);
                            p.println(temp);
                        }

                        p.println("Instructors");
                        for(int k = 0; k < instructors.size(); k++)
                        {
                            temp = instructors.get(k).toString();
                            temp = decrypt(temp);
                            p.println(temp);
                        }

                        p.close();
                }
                catch (Exception e)
                {
                        System.err.println ("Error writing to file");
                }
        }
     

	/*
	 * Returns the current list of instructors in the database as strings
	 */
	public String viewInstructors()
	{
		String instructorList = "";

		for (int i = 0; i < instructors.size(); i++)
		{
			instructorList += instructors.get(i).getID() + "\n";
		}

		return instructorList;
	}

    /*
     *  Returns instructors as an arraylist
     */

    public ArrayList<Instructor> getInstructors(){
        return instructors;
    }

	/*
	 * Returns the current list of students in the database as strings
	 */
	public String viewStudents()
	{
		String studentList = "";

		for (int i = 0; i < students.size(); i++)
		{
			studentList += students.get(i) + "\n";
		}

		return studentList;
	}

    /*
     *  Returns students as an arraylist
     */

    public ArrayList<Student> getStudents(){
        return students;
    }

	/*
	 * Returns the current list of administrators in the database.
	 */
	public String viewAdministrators()
	{
		String administratorList = "";

		for (int i = 0; i < administrators.size(); i++)
		{
			administratorList += administrators.get(i).getID() + "\n";
		}

		return administratorList;
	}

    /*
     *  Returns administrators as an arraylist
     */

    public ArrayList<Administrator> getAdmins(){
        return administrators;
    }

	/*
	 * Checks for the specified username and password and returns true if the user can log in or
	 * returns false if he cannot.  The user type is determined by the type parameter.
	 */
	public boolean verifyUser(String ID, String password, int type)
	{
		boolean isUser = false;

		// 0 - student
		if (type == 0)
		{
			for (int i = 0; i < students.size(); i++)
			{
				if (students.get(i).getID().equals(ID))
				{
					isUser = true;
					break;
				}
			}
		}
		// 1 - instructor
		else if (type == 1)
		{
			for (int i = 0; i < instructors.size(); i++)
			{
				if (instructors.get(i).getID().equals(ID))
				{
					if (instructors.get(i).getPass().equals(password))
					{
						isUser = true;
					}
					else
					{
						isUser = false;
					}
					break;
				}
			}
		}
		// 2 - administrator
		else if (type == 2)
		{
			for (int i = 0; i < administrators.size(); i++)
			{
				if (administrators.get(i).getID().equals(ID))
				{
					if (administrators.get(i).getPass().equals(password))
					{
						isUser = true;
					}
					else
					{
						isUser = false;
					}
					break;
				}
			}
		}

		return isUser;
	}

    /** Applies an encryption algorithm on the database.
     *
     * @param takes a string to be encrypted or decrypted
     * @return returns the parameter after it has been encrypted/decrypted
     */
    private String decrypt(String temp)
    {
        String newString = "";
        for (int l = 0; l < temp.length(); l++)
        {
            char c = temp.charAt(l);
            if       (c >= 'a' && c <= 'm') c += 13;
            else if  (c >= 'n' && c <= 'z') c -= 13;
            else if  (c >= 'A' && c <= 'M') c += 13;
            else if  (c >= 'A' && c <= 'Z') c -= 13;

            newString+= c;
        }
        return newString;
    }

	/*
	 * Returns the learning style associated with the provided student ID number.
	 */
	public String findLearningStyle(String ID)
	{
        String learningStyle = "";
		for (int i = 0; i < students.size(); i++)
		{
			if (students.get(i).getID().equals(ID))
			{
				learningStyle =  students.get(i).getStyle();
			}
		}
        return learningStyle;
	}
}
